package com.es.hotel.controller;

import com.es.hotel.constants.HotelMqConstants;
import com.es.hotel.pojo.Hotel;
import com.es.hotel.query.PageResult;
import com.es.hotel.query.RequestParams;
import com.es.hotel.service.IHotelService;
import com.es.hotel.service.impl.HotelService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/hotel")
public class HotelController {

    @Autowired
    private HotelService hotelService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("list")
    public PageResult search(@RequestBody RequestParams params) {
        return hotelService.search(params);
    }

    //查询出来页面搜索信息并且进行分组,可以结合输入条件进行分组
    @PostMapping("/agg")
    public Map<String, List<String>> agg(@RequestBody RequestParams params) {
        return hotelService.agg(params);
    }

    //实现自动补全功能
    @GetMapping("suggestion")
    public List<String> getSuggestion(@RequestParam("key") String key) {
        return hotelService.getSuggestion(key);
    }


    @PostMapping
    public void saveHotel(@RequestBody Hotel hotel){
        // 新增酒店
        hotelService.save(hotel);
        // 将消息发送到 Redis Stream
        sendHotelMessageToRedisStream(hotel);
    }

    @PostMapping("updateById")
    public void updateById(@RequestBody Hotel hotel) {
        if (hotel.getId() == null) {
            throw new InvalidParameterException("id不能为空");
        }
        hotelService.updateById(hotel);

        // 将消息发送到 Redis Stream
        sendHotelMessageToRedisStream(hotel);
    }

    private void sendHotelMessageToRedisStream(Hotel hotel) {
        // 创建一个消息 Map，用来封装数据
        Map<String, String> messageMap = new HashMap<>();
        messageMap.put("hotelId", hotel.getId().toString());

        // 将消息添加到 Redis Stream 中
        stringRedisTemplate.opsForStream().add(HotelMqConstants.HOTEL_STREAM_KEY, messageMap);
    }

}
